var session=null ,startedSession=false,publisher =null;  
define([
  'jquery',
  'jqueryui',
  'underscore',
  'backbone',
  'lightboxme',
  'dateformatter',
  'multiselect',
  'multiselectfilter',
  'ckeditor',
 /* 'tokbox',*/
  'models/videosession/VideoSessionModel',
  'text!templates/videosession/startsessionTemplate.html'
], function($,JQueryUI, _, Backbone,LightBoxMe,Dateformatter,Multiselect,Multiselectfilter,ck,/*Tokbox,*/ VideoSessionModel, startsessionTemplate){

  var DoctorView = Backbone.View.extend({
    el: $(".modal"),
   // model: new VideoSessionModel(),
/*    events: { "change #profiles" :"addProfile",
    		"change #examinations" :"addType",
    		'click #savePrescription' : 'savePrescription',
    		'click .videoimg' : 'startVideo'} ,*/
    render: function(appointment){
    	if(appointment.get('sessionId')){
            var data = {
            		  session: appointment,
            	        _: _ 
            	      };
     		      this.loadTemplate(data);
    		
    	}else{
            var lOptions = {};
            var self=this;
            this.model = new VideoSessionModel({id: appointment.get('id')});
            lOptions.success = function(){
                var data = {
              		  session: self.model,
              	        _: _ 
              	      };
       		      self.loadTemplate(data);
            };
            this.model.fetch(lOptions);
    		
    	}
    },
    loadTemplate: function(data){
	      var compiledTemplate = _.template( startsessionTemplate, null );
	      this.$el.html(compiledTemplate);
	      $('#videoPanel').dialog({ width: 730,height:600, resizable: true,
	    	  	position: { my: "right top", at: "right top", of: window } ,
	      		beforeClose: function( event, ui ) {
	      			if (publisher) {
	      			    session.unpublish(publisher);
	      			}
	      			publisher = null;
	      		},
	      		open: function( event, ui ) {
	      			if(!session){
		    	    	TB.setLogLevel(TB.DEBUG);
		    	        session = TB.initSession(data.session.get('sessionId'));
		    	        session.addEventListener('sessionConnected', sessionConnectedHandler);
		    	        session.addEventListener('streamCreated', streamCreatedHandler);
		    	        session.addEventListener("resize", publisherResizeHandler);
		    	        session.connect("23104692", data.session.get('tokenId'));
	      			}
	      		}
	      });
    }
  });

  return DoctorView;
});


function sessionConnectedHandler(event) {
	if(!startedSession){
		var publisherProps = {width: 100, height: 80};
	    publisher = TB.initPublisher("23104692", 'myself',publisherProps);
	    session.publish(publisher);

	    // Subscribe to streams that were in the session when we connected
	    subscribeToStreams(event.streams);
	    startedSession=true;
	}
  }

function streamCreatedHandler(event) {
    // Subscribe to any new streams that are created
    subscribeToStreams(event.streams);
  }

function subscribeToStreams(streams) {
    for (var i = 0; i < streams.length; i++) {
      // Make sure we don't subscribe to ourself
    	console.log(streams[i].connection.connectionId +" "+ session.connection.connectionId);
      if (streams[i].connection.connectionId == session.connection.connectionId) {
        return;
      }
      // Subscribe to the stream
  	var subscriberProps = {width: 600, height: 400};

      session.subscribe(streams[i], 'other',subscriberProps);
    }
  }
function publisherResizeHandler(event) {
    newWidth = event.widthTo;
    newHeight = event.heightTo;
    // Modify the UI based on the new dimensions of the publisher 
}